package com.example.spareparts.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class QRCodeGenerator {

    public static String generateQRCode(String text, int width, int height) throws WriterException, IOException {
        // 设置二维码参数
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE,
                width, height, java.util.Map.of(
                        EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L,
                        EncodeHintType.CHARACTER_SET, "UTF-8"
                ));

        // 生成图片
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // 转为 Base64 字符串，便于前端展示
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "PNG", os);
        return Base64.getEncoder().encodeToString(os.toByteArray());
    }
}
